package com.gsnd.gsnd22estore.service.impl;


import com.gsnd.gsnd22estore.domain.EsAddress;
import com.gsnd.gsnd22estore.domain.EsUser;
import com.gsnd.gsnd22estore.dto.extend.AddressExtend;
import com.gsnd.gsnd22estore.mapper.EsAddressMapper;
import com.gsnd.gsnd22estore.mapper.EsUserMapper;
import com.gsnd.gsnd22estore.service.AddressService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

@Service
public class AddressServiceImpl implements AddressService {
    @Autowired
    EsAddressMapper addressMapper;
    @Autowired
    EsUserMapper userMapper;

    @Override
    public List<AddressExtend> getAllAddressByUserId(Integer userId) {
        List<AddressExtend> esAddresses = addressMapper.selectByUserId(userId);
        // 查出当前用户的默认地址
        EsUser esUser = userMapper.selectDetailById(userId);
        return esAddresses.stream().peek(s -> {
            if (s.getId().equals(esUser.getDefaultAddressId())) {
                s.setDefaultValue(true);
            }
        }).collect(Collectors.toList());
    }

    @Override
    public void createAddress(EsAddress address) {
        addressMapper.insert(address);
    }

    @Override
    public void removeAddressById(Integer id) {
        addressMapper.delete(id);
    }

    @Override
    public void editAddressInfo(EsAddress address) {
        addressMapper.update(address);
    }

    @Override
    public void changeDefaultAddress(Integer addressId, Integer userId) {
        addressMapper.updateDefault(addressId,userId);
    }
}
